package ua.com.softway.db;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.ejb.Ejb3Configuration;

public class Persistence {
    private static ThreadLocal<EntityManager> currentEntityManager = new ThreadLocal<EntityManager>();
    private static EntityManagerFactory entityManagerFactory;

    public static void setCurrentEntityManager(EntityManager entityManager) {
        currentEntityManager.set(entityManager);
    }

    public static EntityManager current() {
        return currentEntityManager.get();
    }

    private static Class<?>[] persistentClasses = new Class<?>[0];
    private static String config = "hibernate.cfg.xml";
    
    public static void configure(String config, Class<?> ... persistentClasses) {
        Persistence.config = config;
        Persistence.persistentClasses = persistentClasses;
    }
    
    public static void init() {
        Ejb3Configuration configuration = new Ejb3Configuration();
        
        configuration.configure(config);
        
        for (Class<?> cls : persistentClasses)
            configuration.addAnnotatedClass(cls);
        
        init(configuration.buildEntityManagerFactory());
    }
    
    public static void init(EntityManagerFactory entityManagerFactory) {
        Persistence.entityManagerFactory = entityManagerFactory;
    }

    public static EntityManagerFactory getEntityManagerFactory() {
        if (entityManagerFactory == null) throw new IllegalStateException("Call init()");
        
        return entityManagerFactory;
    }

    public static Criteria createCriteria(Class<?> entityClass) {
        Session session = (Session) current().getDelegate();
        
        return session.createCriteria(entityClass);
    }
}
